<template>
    <div class="alumni-publish-edit">
        <nav-header>
            <template slot="menuBefore">
                <!-- <li><router-link to="/life/alumni/alumni-list" tag="a">校友服务</router-link></li> -->
                <li><a class="pointer" @click=turn>校友服务</a></li>
                <li class="gap">&gt;</li>
            </template>
            <li v-if="this.$route.params.id">文章编辑</li>
        </nav-header>
        <div class="alumni-publish-edit-main" v-loading="loading.status" :element-loading-text="loading.txt">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" v-loading="saveUploading.status" :element-loading-text="saveUploading.txt" v-loading.fullscreen.lock="saveUploading.full">
                <el-form-item label="文章标题" prop="title">
                    <el-input v-model="ruleForm.title" placeholder="输入文章标题，最多30个字符" maxLength="30" ></el-input>
                </el-form-item>
                <el-form-item label="文章内容" prop="content">
                    <!-- <div v-html="ruleForm.content" ref="wordsLength"></div> -->
                    <el-input v-model="ruleForm.content" class="input-hidden" ></el-input>
                    <tinymce
                        id="artical-tinymce"
                        :plugins="plugins"
                        :other_options="options"
                        :toolbar1="toolbar1"
                        :toolbar2="toolbar2"
                        v-model="ruleForm.content"></tinymce>
                    <span class="nubxx">{{wordsLength}} / {{maxLength}}</span>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">保存文章</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<script>
    // import videMsg from '../../resources/video-management/video-list/video-mark.vue'
    import tinymce from 'vue-tinymce-editor';
    import axios from '../../../tools/axios';

    export default {
        data() {
            return {
                content: document.createElement('div'),   // 创建一个dom节点，用于接收富文本中的内容并计算字数的多少
                editId:'',     // 存放编辑文章的id
                maxLength: 5000,
                // 加载数据时显示的信息和加载动画
                loading:{
                    status:false,
                    txt:'获取数据...',
                },
                initData:{      // 文章编辑时用于存放文章的初始信息
                    title: '',
                    content: '',
                },
                ruleForm: {
                    title: '',
                    content: '',
                },
                rules: {
                    title: [
                        { required: true, message: '请输入文章标题', trigger: 'blur' },
                        // { min: 0, max: 30, message: '长度在 0 到 30 个字符', trigger: 'blur' }
                    ],
                    content: [
                        { required: true, message: '请输入文章内容', trigger: 'blur' },
                        // { min: 0, max: 5000, message: '长度在 0 到 5000 个字符', trigger: 'blur' }
                    ],
                },
                wordsLength: 0,   // 统计输入框的字数
                // 发布或者修改文章时的加载信息和动画
                saveUploading:{
                    status: false ,
                    txt:"正在保存...",
                    full:false
                },
                // 以下是富文本的相关参数
                // plugins:['paste','fullscreen','link' ],
                plugins:['paste','fullscreen','link' ,'image'],
                options:{
                    images_upload_handler:this.images_upload_handler,
                    language_url: '/static/tinymce_languages/zh_CN.js',
                    images_upload_url:this.BASE_URL+'/api/alumni/alumniAddPicture',
                    paste_data_images: true,                  // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
                    paste_convert_word_fake_lists: false,     // 插入word文档需要该属性
                    paste_webkit_styles: 'all',
                    paste_merge_formats: true,
                    nonbreaking_force_tab: false,
                    paste_auto_cleanup_on_paste: false,
                    convert_urls: false,
                    font_formats: `
                        微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;
                        宋体='宋体',Helvetica,Arial,sans-serif;
                        仿宋='仿宋',Helvetica,Arial,sans-serif;
                        楷体='楷体',Helvetica,Arial,sans-serif;
                        黑体='黑体',Helvetica,Arial,sans-serif;
                        幼圆='幼圆',Helvetica,Arial,sans-serif;
                        隶书='隶书',Helvetica,Arial,sans-serif;
                        华文新魏='华文新魏',Helvetica,Arial,sans-serif;
                        苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;
                        Arial='Arial',Helvetica,Arial,sans-serif;
                        Verdana=verdana,geneva;
                        Webdings=webdings
                    `,
                },
                toolbar1: 'paste,fullscreen,link,image',
                toolbar2: 'table |insertfile undo redo | formatselect  | fontsizeselect | forecolor backcolor | fontselect bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | link | image | removeformat',
                repeatRequire: false,   // 当点击保存文章后且在请求成功或失败之前此值为true
            }
        },
        components: {
            tinymce
        },
        created(){
            if(this.$route.params.id){
                var editId = this.$route.params.id;
                this.editId = editId;
                this.getData(editId);
            }
        },
        methods: {
            turn(){
                this.$router.back()
                // var title = this.ruleForm.title === this.initData.title;
                // var content = this.ruleForm.content === this.initData.content;

                // // 当标题和内容都没有改变时直接跳转，反则痰喘提醒
                // if(title && content){
                //     this.$router.replace('/life/alumni/alumni-list')
                // }else{
                //     let yes = ( data => {
                //         console.log('是')
                //         console.log(this.ruleForm)
                //     })
                //     let cancel = ( data => {console.log('否')})
                //     this.e_confirm({yes:yes,cancel:cancel,txt:'文章未保存，是否现在保存？'}); 
                // }

            },
            // 获取编辑文章的信息
            getData(id){
                var listParam = {
                    id:id
                }

                // 显示加载动画
                this.loading.status = true;
                let success = (res=>{
                    // 隐藏加载动画
                    this.loading.status = false;

                    var data = res.data;

                    this.initData.title = this.ruleForm.title = data.title;
                    this.initData.content = this.ruleForm.content = data.content;

                })
                let fail = ( data => {
                    // 隐藏加载动画
                    this.loading.status = false;
                })
                //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
                this.$ajax.get('api/alumni/alumniNews',{params: listParam,func:{success:success,fail:fail}})
            },
            submitForm(formName) {
                if(this.repeatRequire){
                    return
                }

                this.$refs[formName].validate((valid,obj) => {
                    var content = this.ruleForm.content;
                    var reg = /<p>(&nbsp;)*(\s&nbsp;)*(&nbsp;)*<\/\s*p>/g
                    content = content.replace(reg,'')
                    content = content.replace(/\s/g,'')
                    if(!content){
                        this.$message.error('文章内容不能为空')
                        return false;
                    }

                    if(this.wordsLength > this.maxLength){
                        this.$message.warning('文章内容最多只能输入' + this.maxLength + '个字符');
                        return
                    }

                    if (valid) {
                        // 发请求
                        this.saveUploading.status = true;
                        this.saveUploading.full = true;
                        this.repeatRequire = true;

                        let success = (data => {
                            this.saveUploading.status = false;
                            this.saveUploading.full = false;
                            this.$message.success(data.msg);
                            setTimeout(()=>{
                                this.$router.back();
                                this.repeatRequire = false;
                            },1500)
                        })

                        let fail = (data => {
                            this.$message.error(data.msg)
                            this.saveUploading.status = false;
                            this.saveUploading.full = false;
                            this.repeatRequire = false;
                        })

                        // 声明一个变量用于存放请求头信息
                        var data = {};
                        data.title   = this.ruleForm.title ;
                        data.content = this.ruleForm.content;

                        if(this.editId){
                            data.id = this.editId;
                            this.$ajax.put('api/alumni/alumniNews',data,{func:{success:success,fail:fail}})
                        }else{
                            data.create_id = this.$g.user_id;
                            data.type = 2;
                            this.$ajax.post('api/alumni/alumniNews',data,{func:{success:success,fail:fail}})
                        }
                    } else {
                        return false;
                    }
                });
            },
            // tinyMac富文本图片上传的方法
            // 图片上传三个参数，图片数据，成功时的回调函数，失败时的回调函数
            images_upload_handler (blobInfo, success, failure) {
                if( blobInfo.blob().type.indexOf('image/')  === -1 ){
                    failure('只允许上传图片格式的文件')
                }else if( blobInfo.blob().size >  10240000 ) {
                    failure('图片大小不能超过10M')
                }else{
                    let formData = new FormData();
                        formData.append( 'file', blobInfo.blob() , blobInfo.filename() );

                    function getData(data){
                        return data.data ? getData(data.data) : data;
                    }
                        
                    let succ = ( data => {
                        data = getData(data);
                        success(this.BASE_URL + data)
                    });
                    let fail = ( data => {
                        data = getData(data);
                        failure(data.message)
                    });
                    //******************************TODO 不知为何要重新create*****************//
                    const instance = axios.create({
                        headers:{
                            Authorization:`Bearer ${this.$g.access_token}`,
                            DecisionPlatform :` ${this.$g.access_token}`,
                            token : sessionStorage.getItem('token'),
                        },
                        withCredentials: true,
                     }) 
                    instance.post('api/alumni/alumniAddPicture',formData).then( succ ).catch(fail)
                }
            },  
        },
        watch:{
            // 监听用户输入的内容长度和做相应的字数限制
            'ruleForm.content'(newVal, oldVal){
                setTimeout(() => {
                    this.content.innerHTML = newVal;

                    // 获取新内容的文章长度
                    let newLen = this.content.textContent.length;

                    this.content.innerHTML = oldVal;

                    // 获取旧内容的文章长度
                    let oldLen = this.content.textContent.length;

                    if(newLen > this.maxLength){
                        // 清空还没有消失的message提示
                        this.$message.closeAll();
                        this.$message.warning('文章内容最多只能输入' + this.maxLength + '个字符');
                        this.ruleForm.content = oldVal;
                        this.wordsLength = this.maxLength;
                    }else{
                        this.wordsLength = newLen;
                    }
                }, 300);
            }
        },
        computed:{
            // wordsLength(){
            //     let content = this.ruleForm.content;
            //     this.content.innerHTML = content;
            //     content = this.content.textContent;

            //     if(content.length > this.maxLength){
            //         this.$message.closeAll();
            //         this.$message.warning('文章内容最多只能输入' + this.maxLength + '个字符');
            //         let children = this.content.children;
            //     }

            //     return content.length
            // }
        }
    }
</script>
<style lang="scss">
    .alumni-publish-edit {
        .alumni-publish-edit-main{
            .el-form{
                .el-form-item{
                    .el-form-item__content{
                        .input-hidden{
                            width:0;
                            height:0;
                            display:none;
                        }
                        .mce-tinymce.mce-container.mce-panel{
                            padding-bottom:30px;
                            .mce-container-body.mce-stack-layout{
                                .mce-top-part.mce-container.mce-stack-layout-item.mce-first{
                                    .mce-container-body{
                                        .mce-container.mce-menubar.mce-toolbar.mce-first{
                                            display:none;
                                        }
                                        .mce-toolbar-grp.mce-container.mce-panel.mce-last{
                                            .mce-container-body.mce-stack-layout{
                                                .mce-container.mce-toolbar.mce-stack-layout-item.mce-first{
                                                    display:none;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            .mce-edit-area.mce-container.mce-panel.mce-stack-layout-item>iframe{
                                height:445px !important; 
                            }
                            .mce-statusbar.mce-container.mce-panel.mce-stack-layout-item.mce-last{
                                display:none;
                            }
                        }
                        .nubxx{
                            box-sizing:border-box;
                            position: absolute;
                            bottom: 1px;
                            left:50%;
                            margin-left:1px;
                            padding-right:35px;
                            width:calc(100% - 1px);
                            height:30px;
                            background: #F9F9F9;
                            transform:translateX(-50%);
                            font-size: 12px;
                            color: #999;
                            text-align:right;
                        }
                    }
                }
            }
        }
        .pointer{
            cursor:pointer;
        }
    }
</style>